﻿using LibreHardwareMonitor.Hardware;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FanMotionWink
{
    public class HardwareUtils
    {
        public class UpdateVisitor : IVisitor
        {
            public void VisitComputer(IComputer computer)
            {
                computer.Traverse(this);
            }
            public void VisitHardware(IHardware hardware)
            {
                hardware.Update();
                foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
            }
            public void VisitSensor(ISensor sensor) { }
            public void VisitParameter(IParameter parameter) { }
        }

        static Computer? computer = null;

        public static void Init()
        {
            if (HardwareUtils.computer != null)
            {
                return;
            }

            Computer computer = new Computer
            {
                IsCpuEnabled = true,
                IsMotherboardEnabled = true,
            };

            computer.Open();
            computer.Accept(new UpdateVisitor());
            HardwareUtils.computer = computer;
        }

        public static void InitUpdateLoop()
        {
            new Thread(() =>
            {
                while (true)
                {
                    Update();
                    Thread.Sleep(1000);
                }
            }).Start();
        }

        public static void Update()
        {
            //Computer computer = new Computer
            //{
            //    IsCpuEnabled = true,
            //    IsMotherboardEnabled = true,
            //};
            computer?.Accept(new UpdateVisitor());
            //HardwareUtils.computer = computer;
        }

        public static void Close()
        {
            try
            {
                computer?.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            computer = null;
        }

        public static Computer Computer
        {
            get
            {
                Init();
                return HardwareUtils.computer;
            }
        }


        static AutoReleaseResourceCloser arrc = new AutoReleaseResourceCloser();
        public class AutoReleaseResourceCloser : IDisposable
        {
            // IDisposable 接口的实现
            public void Dispose()
            {
                // 释放资源的代码
                HardwareUtils.Close();
            }
        }
    }
}
